#include <bits/stdc++.h>
using namespace std;

void work() {
  int n, k, language;
  cin >> n >> k >> language;
  vector<int> song;
  int res = 0;
  for (int i = 0; i < n; i++) {
    int m, l;
    cin >> m >> l;
    if (l == language) {
      song.push_back(m);
    }
  }
  if (song.size() < k) {
    res = -1;
  } else {
    sort(song.begin(), song.end(), greater<int>());
    for (int i = 0; i < k; i++) {
      res += song[i];
    }
  }
  cout << res << endl;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    work();
  }
  return 0;
}